<?php

//商品栏目
if(!defined('IN_T')){
   die('hacking attempt');
}

$id = get_company_id();

//查看栏目列表
if($act == "index"){
	$res = productCatList($id);
	$tp->assign('list',$res);
}
//编辑商品分类
else if($act == "detail"){
	$product_cat_id = intval($_REQUEST['product_cat_id']);
	//验证$product_cat_id是否合法
	$product_cat = $Db->query("SELECT * FROM ".$Base->table('company_product_cat')." WHERE id = $product_cat_id","Row");
	if(empty($product_cat)){
		$product_cat_id = 0;
	}
	//前台显示
	if(empty($_POST)){
		//展示所有分类
		$classification = $Db->query("SELECT * FROM ".$Base->table('company_product_cat')." WHERE cid=$id AND pid=0 ORDER BY  sort DESC , id");
		
		$tp->assign('product_cat',$product_cat);
		$tp->assign('classification',$classification);
		
	}
	//后台数据处理
	else{
		$res['status'] = 0;
		$data = array(
			'name'=>Common::sfilter($_POST['name']),
			'sort'=>intval($_POST['sort']),
			'pid'=>intval($_POST['pid']),
			'is_book'=>intval($_POST['is_book']),
			'unit'=>Common::sfilter($_POST['unit']),
			'cid'=>$id
		);

		if(empty($data['name'])){
			$res['msg'] = '业务名称不能为空';
		}
		//子分类不允许再添加子分类
		else if($data['pid']>0 && $Db->query("select pid from ".$Base->table('company_product_cat')." where id=".$data['pid']."",'One')){
			$res['msg'] = '上线分类是子分类，不能再添加子分类';
		}
		else{
			if($product_cat_id){
				$Db->update($Base->table('company_product_cat'),$data,array('id'=>$product_cat_id));
			}
			else{
				$product_cat_id = $Db->insert($Base->table('company_product_cat'),$data);
			}
			$res = array('status'=>1,'msg'=>'提交成功','href'=>'/'.COMPANY_PATH.'/?m=product_cat');
		}
		echo $Json->encode($res);
		exit;
	}
}
//删除栏目分类
else if($act =="delete"){
	$id = intval($_POST['product_cat_id']);
	// var_dump($id);
	$res['status'] = 0;
	//检测是否是一级类目且有小类
	$ids = $Db->query("SELECT id FROM ".$Base->table('company_product_cat')." WHERE id=$id or pid=$id");
	foreach($ids as $k=>$v){
		$product_cat_id[]=$v['id'];
	}
	$product_cat_ids = implode(',',$product_cat_id);
	//验证该类目下有没有商品
	if($Db->query("SELECT id FROM ".$Base->table('company_product')." WHERE cat_id IN (".$product_cat_ids.") ")){
		$res['msg'] = '该类目下有商品,无法删除';
	}
	else if(count($product_cat_id)>1){
		$res['msg'] = '该类顶级类目下有二级类目,无法删除';
	}
	else{
		//验证是否是非法操作
		$Db->execSql("delete from ".$Base->table('company_product_cat')." where id=$id ");
		$res['status'] = 1;
	}
	echo $Json->encode($res);
	exit;
}

$tp->assign('nav','营业特色');
$tp->assign('act',$act);

function productCatList($id){
	$sql = "SELECT * FROM ".$GLOBALS['Base']->table('company_product_cat')." WHERE cid=$id and pid=0 ORDER BY  sort asc , id asc";
	$list = $GLOBALS['Db']->query($sql);
	foreach($list as $k=>$v){
		$sql = "select * from ".$GLOBALS['Base']->table('company_product_cat')." where pid=".$v['id']." order by sort asc,id asc";
		$list[$k]['subs'] = $GLOBALS['Db']->query($sql);
	}
	return array('list'=>$list);
}

?>